﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using mp.message.resp;
using TB.Entity;
using TB.BLL;
using System.Configuration;

namespace mp.message.util
{
    /// <summary>
    /// 核心服务类 
    /// </summary>
    public class CoreService
    {
        /// <summary>
        /// 处理微信发来的请求 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static String ProcessRequest(System.Web.HttpRequest request)
        {
            String respXmlMessage = null; //返回给用户的XML数据

            TB.BLL.MpReqMsg reqMsgBll = new TB.BLL.MpReqMsg();
            TB.Entity.MpReqMsg reqMsgEntity = new TB.Entity.MpReqMsg();

            TB.Entity.MpRespMsg respMsgEntity = new TB.Entity.MpRespMsg();
            TB.BLL.MpRespMsg respMsgBll = new TB.BLL.MpRespMsg();

            TB.Entity.MpUserInfo userEntity = new TB.Entity.MpUserInfo();
            TB.BLL.MpUserInfo userBll = new TB.BLL.MpUserInfo();

            try
            {
                //String respContent = "请求处理异常，请稍候尝试！";// 默认返回的文本消息内容  
                Dictionary<String, String> requestDic = MessageUtil.ParseXml(request);// xml请求解析  
                //foreach (KeyValuePair<string, string> xx in requestDic)
                //{
                //    CommonFun.PrintLog("xx", xx.Key + "=" + xx.Value);
                //}
                //测试代码构造 start
                //Dictionary<String, String> requestDic = new Dictionary<string, string>();
                //requestDic["ToUserName"] = "gh_b75d9be701b5";
                //requestDic["FromUserName"] = "oZSGWjlAwi9GGVVln7IjNZXWN-EoLHLXXXXX";
                //requestDic["CreateTime"] = "1378448933";
                //requestDic["MsgType"] = "text";
                ////requestDic["Event"] = "subscribe";
                //requestDic["Content"] = "XXXXX";
                //测试代码构造 end

                String fromUserName = requestDic["FromUserName"];// 发送方帐号（open_id）  
                String toUserName = requestDic["ToUserName"];// 公众帐号  
                String msgType = requestDic["MsgType"]; // 消息类型  
                String createTime = CommonFun.CreateTime(requestDic["CreateTime"]).ToString();//请求消息的时间
                String realToUserName = System.Configuration.ConfigurationManager.AppSettings[toUserName];
                //如果数据库没该用户写入该用户
                if (!userBll.IsExist(toUserName, fromUserName))
                {
                    userEntity.toUserName = toUserName;
                    userEntity.fromUserName = fromUserName;
                    userEntity.createTime = createTime;
                    if (msgType.Equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT))
                    {
                        userEntity.subscribe = "subscribe";
                    }
                    else
                    {
                        userEntity.subscribe = "subscribe_0";
                    }
                    userEntity.realToUserName = realToUserName;
                    userBll.InsertSubscribeUser(userEntity);
                }//////////////////////////////////////////
                //获取微信发来的POST XML基本信息(对于网站系统是一次用户请求)
                reqMsgEntity.toUserName = toUserName;
                reqMsgEntity.fromUserName = fromUserName;
                reqMsgEntity.createTime = createTime;
                reqMsgEntity.msgType = msgType;

                // 文本消息  
                if (msgType.Equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT))
                {
                    //将文本消息插入数据库,如果不是关键词消息就写入数据库，否则返回相应的链接
                    reqMsgEntity.text_Content = requestDic["Content"];
                    string keyword=reqMsgEntity.text_Content;
                    //List<TB.Entity.MpRespMsg> list = respMsgBll.LoadAllByKeyword(reqMsgEntity.text_Content);
                    List<string> listMsgType = new List<string>();
                    if (respMsgBll.IsKeywordExist(keyword, listMsgType))//存在则返回数据库的消息组合(text,music,news三种消息)
                    {
                        //此处要考虑数据库的约束，可能出的情况是如 "33"这个关键词同时存在于text,music,news消息中
                        //但回复消息时只能回复一种消息。因此在数据库添加数据数据时要考虑到。如果某关键词同时存在
                        //于多个消息字段中优先返回news消息。

                        if (listMsgType.Count == 1)  //得到确定的回复消息的类型
                        {
                            string strMsgType = listMsgType[0];
                            if (strMsgType == "text")
                            {
                                string content = respMsgBll.GetRespTextMessage(keyword);
                                respXmlMessage = MessageUtil.RespXmlTextMessage(toUserName,fromUserName,content);
                            }
                            else if (strMsgType == "music")
                            {//对于音乐返回只能有一条数据。数据库约束时不能对应多个关键词
                                
                                Dictionary<string, string> musicDict = respMsgBll.GetRespMusicMessage(keyword);
                                respXmlMessage = MessageUtil.RespXmlMusicMessage(toUserName,fromUserName,musicDict);
                            }
                            else if (strMsgType == "news")
                            {//如果回复是1-9的数字，则组合1,11,12,13--19这样的NewsMessage回复，
                                if (keyword.Length == 1) //保证长度为1
                                {
                                    char[] ch = keyword.ToCharArray(); //转化为字符类型
                                    if (ch[0] >= 49 && ch[0] <= 57) //保证字符的ASCI码在49--57之间
                                    {
                                        string[] key = new string[10];
                                        key[0] = keyword;
                                        for (int i = 1; i < 10; i++)
                                            key[i] = keyword + i.ToString();
                                        List<Dictionary<string, string>> dictNewsMsg = respMsgBll.GetRespNewsMessage(key);
                                        respXmlMessage = MessageUtil.RespXmlNewsMessage(toUserName, fromUserName, dictNewsMsg);
                                    }
                                    else
                                    {
                                        //返回数据库关键词查到的NewsMessages消息字典集合
                                        List<Dictionary<string, string>> dictNewsMsg = respMsgBll.GetRespNewsMessage(keyword);
                                        respXmlMessage = MessageUtil.RespXmlNewsMessage(toUserName, fromUserName, dictNewsMsg);  
                                    }
                                }
                                else
                                {
                                    //返回数据库关键词查到的NewsMessages消息字典集合
                                    List<Dictionary<string, string>> dictNewsMsg = respMsgBll.GetRespNewsMessage(keyword);
                                    respXmlMessage = MessageUtil.RespXmlNewsMessage(toUserName, fromUserName, dictNewsMsg);   
                                }
                                //respXmlMessage = MessageUtil.RespXmlNewsMessage(toUserName, fromUserName, dictNewsMsg);   
                            }
                        }
                        else  //多于一种消息类型时则返回news消息
                        {
                            //返回数据库关键词查到的NewsMessages消息字典集合
                            List<Dictionary<string, string>> dictNewsMsg = respMsgBll.GetRespNewsMessage(keyword);
                            respXmlMessage = MessageUtil.RespXmlNewsMessage(toUserName,fromUserName,dictNewsMsg);
                        }
                    }
                    else  //不存在返回微信主菜单并将用户发来的信息存入数据库中。(返回文本消息)
                    {
                        string content =respMsgBll.GetWxMenuStr();
                        respXmlMessage = MessageUtil.RespXmlTextMessage(toUserName, fromUserName, content);
                    }
                    reqMsgBll.InsertReqMsg(reqMsgEntity);
                }
                // 图片消息  
                else if (msgType.Equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE))
                {
                    string content = respMsgBll.GetWxMenuStr();
                    respXmlMessage = MessageUtil.RespXmlTextMessage(toUserName, fromUserName, content);

                    reqMsgEntity.image_PicUrl = requestDic["PicUrl"];
                    reqMsgBll.InsertReqMsg(reqMsgEntity);
                }
                // 地理位置消息  
                else if (msgType.Equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION))
                {
                    string content = respMsgBll.GetWxMenuStr();
                    respXmlMessage = MessageUtil.RespXmlTextMessage(toUserName, fromUserName, content);

                    reqMsgEntity.location_Location_X=requestDic["Location_X"];
                    reqMsgEntity.location_Location_Y =requestDic["Location_Y"];
                    reqMsgEntity.location_Scale=requestDic["Scale"];
                    reqMsgEntity.location_Label = requestDic["Label"];
                    reqMsgBll.InsertReqMsg(reqMsgEntity);
                }
                // 链接消息  
                else if (msgType.Equals(MessageUtil.REQ_MESSAGE_TYPE_LINK))
                {
                    string content = respMsgBll.GetWxMenuStr();
                    respXmlMessage = MessageUtil.RespXmlTextMessage(toUserName, fromUserName, content);
                }
                // 音频消息  
                else if (msgType.Equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE))
                {
                    string content = respMsgBll.GetWxMenuStr();
                    respXmlMessage = MessageUtil.RespXmlTextMessage(toUserName, fromUserName, content);

                    reqMsgEntity.voice_Format = requestDic["Format"];
                    reqMsgEntity.voice_MediaId = requestDic["MediaId"];
                    reqMsgEntity.voice_Recognition = requestDic["Recognition"];
                    reqMsgBll.InsertReqMsg(reqMsgEntity);
                }
                else if (msgType.Equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO))
                {
                    string content = respMsgBll.GetWxMenuStr();
                    respXmlMessage = MessageUtil.RespXmlTextMessage(toUserName, fromUserName, content);

                    reqMsgEntity.video_MediaId=requestDic["MediaId"];
                    reqMsgEntity.video_ThumbMediaId = requestDic["ThumbMediaId"];
                    reqMsgBll.InsertReqMsg(reqMsgEntity);
                }
                // 事件推送  
                else if (msgType.Equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT))
                {
                    // 事件类型  
                    String eventType = requestDic["Event"];
                    // 订阅  
                    if (eventType.Equals(MessageUtil.EVENT_TYPE_SUBSCRIBE))
                    {
                        if (userBll.IsExist(toUserName, fromUserName))
                        {
                            userBll.UpdateSubscribeUser(toUserName, fromUserName,realToUserName,"subscribe", createTime);
                        }
                        string content = respMsgBll.GetWxMenuStr();
                        respXmlMessage = MessageUtil.RespXmlTextMessage(toUserName, fromUserName, content);
                    }
                    // 取消订阅  
                    else if (eventType.Equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE))
                    {
                        userBll.UpdateSubscribeUser(toUserName, fromUserName,realToUserName,"unsubscribe", createTime);
                    }
                    // 自定义菜单点击事件  
                    else if (eventType.Equals(MessageUtil.EVENT_TYPE_CLICK))
                    {
                        // TODO 自定义菜单权没有开放，暂不处理该类消息  
                    }
                }
            }
            catch (Exception ex)
            {
                CommonFun.PrintExceptionLog(ex);
            }
            return respXmlMessage;
        }
    }
}
